﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;


namespace Lamex.mTools.UI
{
    public partial class frmTL_PDFSeparate : Form
    {
        public frmTL_PDFSeparate()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;

            labMaxPageNum.Text = "";
            labSelectInfo.Text = "";
        }
        int iPageNum;
        string filePath = "";
        private void button1_Click(object sender, EventArgs e)
        {
            if (filePath == "")
            {
                MessageBox.Show("选择PDF文件无效！", "文件无效！");
            }
            else
            {
                if (numericUpDownEndPageNum.Value > iPageNum)
                {
                    MessageBox.Show("最大页码值有误！请检查！", "页码有误！");
                }
                else if (numericUpDownStartPageNum.Value < 1)
                {
                    MessageBox.Show("最小页码值有误！请检查！", "页码有误！");
                }
                else if (numericUpDownStartPageNum.Value > numericUpDownEndPageNum.Value)
                {
                    MessageBox.Show("最小页码值比最大页码值大！请检查！", "页码有误！");
                }
                else
                {
                    string splitPDFPath = filePath.Remove(filePath.Length - 4) 
                        + "(" + numericUpDownStartPageNum.Value.ToString() 
                        + "-" + numericUpDownEndPageNum.Value.ToString() 
                        + ").pdf";
                    int startPageNum = int.Parse(numericUpDownStartPageNum.Value.ToString());
                    int endPageNum = int.Parse(numericUpDownEndPageNum.Value.ToString());
                    copypdf(startPageNum, endPageNum, filePath, splitPDFPath);
                    MessageBox.Show("处理完毕，拆分文件保存在当前PDF文件路径！", "提示");
                    this.Close();
                }   
            }
        }

        private void copypdf(int StartPage, int EndPage, string file1, string splitFileName)
            //将file1中页码StartPage到EndPage的文件拷贝至splitFileName          
        {
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file1);
            Document document = new Document(reader.GetPageSizeWithRotation(StartPage));
            //创建document对象
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(splitFileName, FileMode.Create)); 
            //实例化document对象
            document.Open();
            int rotation;
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page;
            while (StartPage <= EndPage)
            {
                document.SetPageSize(reader.GetPageSizeWithRotation(StartPage));
                document.NewPage();
                page = writer.GetImportedPage(reader, StartPage);
                rotation = reader.GetPageRotation(StartPage);
                if (rotation == 90 || rotation == 270)
                {
                    //document.NewPage();
                    if (rotation == 90)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(StartPage).Height);
                    }
                    if (rotation == 270)
                    {
                        cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(StartPage).Width, 0);
                    }
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                StartPage++;
            }
            try
            {
                document.Close();
                reader = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog myBlockDialog = new OpenFileDialog();
            myBlockDialog.Filter = "PDF文件(*.pdf)|*.pdf";
            myBlockDialog.Title = "打开PDF文件";
            myBlockDialog.ShowDialog();

            filePath = myBlockDialog.FileName;
            if (filePath == "")
            {
                MessageBox.Show("选择PDF文件无效！", "文件无效！");
                //Application.Exit();
            }
            labSelectInfo.Text = "当前选择文件为：" + "\r\n" + filePath;

            //iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(filePath);
            Document document = new Document();
            //PdfWriter.GetInstance(document,new FileStream(filePath,FileMode.Open));
            PdfReader reader = new PdfReader(filePath);
            iPageNum = reader.NumberOfPages;
            reader.Close(); //不关闭会一直占用pdf资源，对接下来的操作会有影响
            //PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(splitFileName, FileMode.Create)); 
            //labMaxPageNum.Text = @"/" + iPageNum.ToString();
            labMaxPageNum.Text = "共" + iPageNum.ToString() + "页";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Document doc = new Document(PageSize.A4);
            PdfWriter.GetInstance(doc,new FileStream("test1.pdf",FileMode.Create));
            doc.Open();
            doc.Add(new Paragraph("Hello!"));
            doc.Close();
        }

        private void numericUpDownStartPageNum_ValueChanged(object sender, EventArgs e)
        {
            if (numericUpDownStartPageNum.Value > numericUpDownEndPageNum.Value)
            {
                MessageBox.Show("起始值不能大于结束值","错误提醒",MessageBoxButtons.OK);
                numericUpDownStartPageNum.Value = numericUpDownEndPageNum.Value;
            }
        }

        private void numericUpDownEndPageNum_ValueChanged(object sender, EventArgs e)
        {
            if (numericUpDownEndPageNum.Value < numericUpDownStartPageNum.Value)
            {
                MessageBox.Show("结束值不能小于起始值", "错误提醒", MessageBoxButtons.OK);
                numericUpDownEndPageNum.Value = numericUpDownStartPageNum.Value;
            }

        }
    }
}
